<template>
  <div>
    <el-card>
      <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        status-icon
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
        :model="ruleForm"
      >
        <el-form-item label="新密码" prop="updatePwd">
          <el-input
            type="text"
            v-model="ruleForm.updatePwd"
            autocomplete="off"
            style="width: 180px"
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPwd">
          <el-input
            type="text"
            v-model="ruleForm.confirmPwd"
            autocomplete="off"
            style="width: 180px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)"
            >确认</el-button
          >
          <el-button @click="cancelForm">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import UserAPI from "@/api/user/index";
import { useUserStore } from "@/store";
const userStore = useUserStore();
import type { FormInstance, FormRules } from "element-plus";
import { useRoute, useRouter } from "vue-router";
const $router = useRouter();
const ruleFormRef = ref<FormInstance>();
const ruleForm = ref({
  updatePwd: "",
  confirmPwd: "",
});

const validatePass = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请确认新密码"));
  } else if (value !== ruleForm.value.updatePwd) {
    callback(new Error("两次输入密码不一致"));
  } else {
    callback();
  }
};

const validatePass2 = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请输入新密码"));
  } else if (value.length < 6) {
    callback(new Error("密码不能少于6位数"));
  } else {
    callback();
  }
};
const rules = ref<FormRules<typeof ruleForm>>({
  updatePwd: [{ required: true, trigger: "blur", validator: validatePass2 }],
  confirmPwd: [
    {
      required: true,
      trigger: "blur",
      validator: validatePass,
    },
  ],
});

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (valid) {
      let result = await UserAPI.pwdUpdate({
        newpassword: ruleForm.value.confirmPwd,
      });
      ElMessage({
        message: "修改成功",
        type: "success",
      });

      $router.replace("/personalCenter/updatePersonalInfo");
    } else {
      console.log("error submit!");
    }
  });
};

const cancelForm = () => {
  $router.replace("/personalCenter/updatePersonalInfo");
};
</script>

<style scoped lang="scss"></style>
